package com.sky.controller.admin;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.*;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.SetmealService;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.DishItemVO;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private DishService dishService;


    /**
     * 登录
     *
     * @param userLoginDTO
     * @return
     */
    @PostMapping("user/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("员工登录：{}", userLoginDTO.getCode());

        User user = userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();


        return Result.success(userLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("user/logout")
    public Result logout() {
        log.info("用户退出登录");
        return Result.success();
    }

    /**
     * C端根据分类id查询套餐
     *
     * @param categoryId
     * @return
     */
    @GetMapping("setmeal/list")
    public Result<List<Setmeal>> findSetmealById(Integer categoryId) {
        log.info("C端根据分类id查询套餐:{}", categoryId);
        List<Setmeal> setmeals = setmealService.findByIdC(categoryId);
        return Result.success(setmeals);
    }

    /**
     * C端根据套餐id查询包含的菜品
     *
     * @param id
     * @return
     */
    @GetMapping("setmeal/dish/{id}")
    public Result<List<DishItemVO>> findSetmealDishById(@PathVariable Integer id) {
        log.info("C端根据套餐id查询包含的菜品:{}", id);
        List<DishItemVO> dishItemVOS = setmealService.findSetmealDishById(id);
        return Result.success(dishItemVOS);
    }

    /**
     * C端根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("dish/list")
    public Result<List<Dish>> findDish(Integer categoryId) {
        log.info("根据分类id查询菜品:{}", categoryId);
        List<Dish> dishes = dishService.findDish(categoryId);
        return Result.success(dishes);

    }
}
